#! -*- coding:utf-8 -*-
import logging
from datetime import datetime
from common.bankcard import db as bankcard_db
from common.bankcard.model import BANK_CARD_TYPE, BANK_CARD_STATUS
from common.mch import db as mch_db
from common.recharge.model import REMINDER_TIME
from common.recharge import db as recharge_db
from common.recharge.handler import CHARGE_HANDLE, send_reminder
from django.core.management.base import BaseCommand
from common.utils.tz import date_seconds_ago

_LOGGER = logging.getLogger('recharge')


class Command(BaseCommand):
    def handle(self, **options):

            hour_ago_date = date_seconds_ago(REMINDER_TIME)
            cards = bankcard_db.get_bankcard_by_type_status(BANK_CARD_TYPE.RECHARGE, BANK_CARD_STATUS.AVAILABLE,
                                                            hour_ago_date)
            sent_items = 0
            for card in cards:
                try:
                    orders = recharge_db.recharge_getorder_hour(card.name, hour_ago_date)
                    if orders:
                        if card.mch_id:
                            company = mch_db.get_mch_info(card.mch_id)
                            company_name = ""

                            if company:
                                company_name = company["name"]

                            card_deposit = {
                                "company": company_name,
                                "card_code": card.name,
                                "card_type": BANK_CARD_TYPE.get_label(card.card_type).decode('utf-8'),
                                "level" : orders["level"]
                             }
                            _LOGGER.info('Sending reminder : %s' % card.name)
                            sent = send_reminder(card_deposit)

                            if sent:
                                _LOGGER.info('Reminder sent : %s' % card.name)
                                bankcard_db.update_bankcard_info(card.id, {'reminder_sent_at': datetime.utcnow()})
                                sent_items += 1
                except Exception as e:
                    _LOGGER.exception('Recharge reminder process error.(%s)' % e)

            _LOGGER.info('Total Message Sent : %s' % str(sent_items))

